package com.atguigu.gmall.mq.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //  发送普通消息
    @GetMapping("/sendMsg")
    public Result sendMsg(){
        //  调用发送消息方法
        rabbitService.sendMsg("exchange.confirm","routing.confirm666","来人了，开始接客了.");
        return Result.ok();
    }

    //  发送延迟消息
    @GetMapping("/sendDeadLetterMsg")
    public Result sendDeadLetterMsg(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("发送时间："+simpleDateFormat.format(new Date()));
        //  调用发送消息方法
        rabbitService.sendMsg(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"来人了，开始接客了.");
        return Result.ok();
    }

    //  基于插件发送延迟消息
    @GetMapping("/sendDelayMsg")
    public Result sendDelayMsg(){
        //  设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("发送时间："+simpleDateFormat.format(new Date()));
        //  调用发送消息方法 没有将数据放入缓存
        //  rabbitService.sendMsg(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"来人了，开始接客了.");
        //        没有将数据放入缓存
        //        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay,DelayedMqConfig.routing_delay,"atguigu",
        //                (message)->{
        //                    //  设置延迟时间：10s
        //                    message.getMessageProperties().setDelay(10000);
        //                    return message;
        //                });
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content","atguigu");
        jsonObject.put("uuid", UUID.randomUUID().toString());
        rabbitService.sendDelayMsg(DelayedMqConfig.exchange_delay,DelayedMqConfig.routing_delay,jsonObject,3);

        //  rabbitService.sendDelayMsg(DelayedMqConfig.exchange_delay,DelayedMqConfig.routing_delay,"atguigu",3);

        return Result.ok();
    }
}
